package com.itheima.controller;

import com.itheima.entity.Address;
import com.itheima.entity.PageBean;
import com.itheima.entity.ResultInfo;
import com.itheima.entity.User;
import com.itheima.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.sql.ResultSet;
import java.util.Map;

@RestController
@RequestMapping("/address")
public class AddressController {
    @Autowired
    private AddressService addressService;
    @Autowired
    private HttpSession session;

    protected User getuUserFromSession() {
        return (User) session.getAttribute("user");
    }

    @RequestMapping("/find")
    public PageBean find(@RequestBody Map<String, Object> params) {
        System.out.println("查询参数:" + params);
        User user = getuUserFromSession();
        params.put("uid", user.getUid());
        return addressService.findAddress(params);
    }

    @RequestMapping("/save")
    public ResultInfo save(@RequestBody Address address) {
        User user = getuUserFromSession();
        address.setUid(user.getUid());
        addressService.save(address);
        return new ResultInfo(true, "添加收货地址成功");
    }

    @RequestMapping("/update")
    public ResultInfo update(@RequestBody Address address) {
        addressService.update(address);
        return new ResultInfo(true, "修改地址成功");
    }

    @RequestMapping("/changeDefaultAddress")
    public ResultInfo changeDefaultAddress(Integer aid, HttpSession session) {
        User user = (User) session.getAttribute("user");
        addressService.changeDefaultAddress(user.getUid(), aid);
        return new ResultInfo(true, "修改默认地址成功");
    }

    @RequestMapping("/delete")
    public ResultInfo delete(Integer aid){
        addressService.delete(aid);
        return new ResultInfo(true, "删除成功");
    }
}
